package com.smzd.framework.sso;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.qq.connect.api.OpenID;
import com.qq.connect.api.weibo.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.Avatar;
import com.qq.connect.javabeans.weibo.FansIdolsBean;
import com.qq.connect.javabeans.weibo.SingleFanIdolBean;
import com.qq.connect.javabeans.weibo.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import com.smzd.framework.sso.domain.SocialUser;
import com.smzd.framework.system.domain.UserBind;

public class QQConnectOAuth2AuthenticationProcessor extends OAuth2AuthenticationProcessor {

    public QQConnectOAuth2AuthenticationProcessor() {
        super("qqconn");
        this.platform = UserBind.AUTH_TYPE_QQ_CONNECT;
    }

    @Override
    public Object getAccessToken(String queryString) throws Exception {
        @SuppressWarnings("deprecation")
        AccessToken accessTokenApi = (new Oauth()).getAccessTokenByQueryString(queryString, state);
        System.out.println("accessTokenApi=" + accessTokenApi);
        System.out.println("accessTokenApi.access_token=" + accessTokenApi.getAccessToken());
        System.out.println("accessTokenApi.expire_in=" + accessTokenApi.getExpireIn());
        return accessTokenApi;
    }

    @Override
    public Object getRemoteUserInfo(Object accessToken) throws Exception {
        AccessToken accessTokenApi = (AccessToken) accessToken;
        String access_token = accessTokenApi.getAccessToken();
        System.out.println("access_token=" + access_token);
        OpenID openIdApi = new OpenID(access_token);
        System.out.println("openIdApi=" + access_token);
        String openId = openIdApi.getUserOpenID();
        System.out.println("openId=" + openId);
        UserInfo userInfoApi = new UserInfo(access_token, openId);
        UserInfoBean userInfoBean = userInfoApi.getUserInfo();
        String nickName = userInfoBean.getNickName();
        String gender = userInfoBean.getSeqid();
        Avatar avatar = userInfoBean.getAvatar();
        String url_100 = avatar.getAvatarURL100();
        String url_50 = avatar.getAvatarURL50();
        String url_30 = avatar.getAvatarURL30();
        StringBuffer sb = new StringBuffer();
        int extIntValue = userInfoBean.getFansNum() - userInfoBean.getFavNum();
        sb.append("openid: ").append(openId).append(";access_token: ").append(access_token).append("; gender: ")
                .append(gender).append("; url_100: ").append(url_100).append("; url_50: ").append(url_50)
                .append("; url_30: ").append(url_30);
        SocialUser user = new SocialUser();
        user.setAccessToken(access_token);
        user.setPlatform(this.getPlatform());
        user.setName(nickName);
        user.setPassword(openId);
        user.setOpenid(openId);
        // TODO 这个地方需要下载吗？下载也是网络图片啊，只是在我们的服务器上而已
        user.setAvatar(url_100);
        user.setGender(0);
        user.setDescription(sb.toString());
        user.setExtIntValue(extIntValue);
        return user;
    }

    @Override
    public SocialUser convertRemoteToSocialUser(Object remoteUserInfo) throws Exception {
        SocialUser remoteUser = (SocialUser) remoteUserInfo;
        return remoteUser;
    }

    @SuppressWarnings("deprecation")
    @Override
    public String getAuthenticationURL() throws Exception {
        return new Oauth().getAuthorizeURL("qqconn");
    }

    @Override
    public List<String> getFriendOpenids(SocialUser socialUser, Object accessToken) throws Exception {
        System.out.println("寻找当前用户的社交好友。access_token=" + socialUser.getAccessToken() + ", openid="
                + socialUser.getOpenid());
        com.qq.connect.api.weibo.UserInfo userinfo = new com.qq.connect.api.weibo.UserInfo(socialUser.getAccessToken(),
                socialUser.getOpenid());
        List<String> myfriends = new ArrayList<>();
        if (socialUser.getExtIntValue() > 0) {// fansNumber>favsNumber，偶像比较少，从偶像入手
            System.out.println("由于偶像比较少，我得看看我的偶像们有谁是我的好友");
            FansIdolsBean bean = userinfo.getIdolsList(30, 0, "mode=1");// 获取我的听众
            if (bean.getErrcode() == 0) {
                System.out.println("访问没有出错，很好");
                if (bean.getCurNum() > 0) {
                    System.out.println("返回的数据量不为零，极好！num=" + bean.getCurNum());
                    do {
                        List<SingleFanIdolBean> friends = bean.getFanIdols();
                        for (SingleFanIdolBean f : friends) {
                            System.out.println("逐个检查：" + f.getName() + "[" + f.getNick() + "], openid=" + f.getOpenID()
                                    + ", sex=" + f.getSex());
                            if (f.isFans()) {// 如果这个用户还是我的fans，那么他是我的好友
                                System.out.println("这是我的好友啊！");
                                if (!StringUtils.isEmpty(f.getOpenID())) {
                                    myfriends.add(f.getOpenID());
                                }
                            }
                        }
                        if (!bean.hasNext()) {
                            System.out.println("就这么多了，好友都找完了");
                            break;
                        }
                        int nextStartPos = bean.getNextStartPos();
                        System.out.println("还有更多好友，再取下一个好友列表，开始位置：" + nextStartPos);
                        bean = userinfo.getIdolsList(30, nextStartPos, "mode=1");
                        if (bean.getErrcode() > 0) {
                            System.out.println("出错了！");
                            break;
                        }
                        if (bean.getCurNum() <= 0) {
                            System.out.println("里面没数据了");
                            break;
                        }
                    } while (true);
                    System.out.println("很好，好友都找完了");
                }
            }
        } else {// 还是粉丝数量比较少
            System.out.println("由于听众比较少，我得看看我的听众们有谁是我的好友");
            FansIdolsBean bean = userinfo.getFansList(30, 0, "mode=1");// 获取我的听众
            if (bean.getErrcode() == 0) {
                System.out.println("访问没有出错，很好");
                if (bean.getCurNum() > 0) {
                    System.out.println("返回的数据量不为零，极好！num=" + bean.getCurNum());
                    do {
                        List<SingleFanIdolBean> friends = bean.getFanIdols();
                        for (SingleFanIdolBean f : friends) {
                            System.out.println("逐个检查：" + f.getName() + "[" + f.getNick() + "], openid=" + f.getOpenID()
                                    + ", sex=" + f.getSex());
                            if (f.isIdol()) {// 如果这个用户还是我的偶像，那么他是我的好友
                                System.out.println("这是我的好友啊！");
                                if (!StringUtils.isEmpty(f.getOpenID())) {
                                    myfriends.add(f.getOpenID());
                                }
                            }
                        }
                        if (!bean.hasNext()) {
                            System.out.println("就这么多了，好友都找完了");
                            break;
                        }
                        int nextStartPos = bean.getNextStartPos();
                        System.out.println("还有更多听众，再取下一个好友列表，开始位置：" + nextStartPos);
                        bean = userinfo.getFansList(30, nextStartPos, "mode=1");
                        if (bean.getErrcode() > 0) {
                            System.out.println("出错了！");
                            break;
                        }
                        if (bean.getCurNum() <= 0) {
                            System.out.println("里面没数据了");
                            break;
                        }
                    } while (true);
                    System.out.println("很好，好友都找完了");
                }
            }
        }

        return myfriends;
    }
}
